<template>
     <el-form :model="form" label-width="100px" class="form-container">
         <el-row :gutter="20">
       <!-- 左侧栏 -->
       <el-col :span="8">
         <el-form-item label="单据编号：">
           <el-input 
             v-model="form.docNumber"
             placeholder="请输入"
             clearable
           />
         </el-form-item>
         
         <el-form-item label="单据阶段：">
           <el-select 
             v-model="form.stage"
             placeholder="请选择"
             clearable
           >
             <el-option
               label="已生效"
               value="active"
               :checked="form.stage === 'active'"
             />
             <!-- 其他选项可根据需要添加 -->
           </el-select>
         </el-form-item>
       </el-col>
 
       <!-- 中间栏 -->
       <el-col :span="10">
         <el-form-item label="单据日期：">
           <el-date-picker
             v-model="form.dateRange"
             type="daterange"
             range-separator="至"
             :start-placeholder="form.dateRange[0] || '请选择开始'"
             :end-placeholder="form.dateRange[1] || 'A'"
           />
         </el-form-item>
 
         <el-form-item label="已作废：">
           <el-select v-model="form.invalid" placeholder="否">
             <el-option label="否" value="no" />
             <el-option label="是" value="yes" />
           </el-select>
         </el-form-item>
 
        
       </el-col>
 
       <!-- 右侧操作按钮 -->
       <el-col :span="6" class="action-buttons">
         <el-button type="primary" @click="handleQuery">查</el-button>
         <el-button type="info" @click="handleReset">重</el-button>
         <el-button type="success" @click="toggleCollapse">收</el-button>
       </el-col>
     </el-row>
   </el-form>

    <div>
        <SalesOrderPage
            :table-data="tableData"
            :columns="tableColumns"
            :current-page="pageNo"
            :total="allPage"
            :page-size="pageSize"
            @page-change="handlePageChange"
            @action="handleTableAction"
            @edit="upDateSalesQuotes"
            @selection-change="handleSelectionChangeOrder"
            @row-audit="handleRowAudit"
            @delete="deleteDoc"
        ></SalesOrderPage> 
    </div>
<el-dialog
    v-model="auditDialogVisible"
    title="单据审核"
    width="600px"
    :close-on-click-modal="false"
>
    <el-form :model="auditForm" :rules="auditRules" ref="auditFormRef">
        <el-form-item label="单据编号：" prop="docCode">
            <el-input
                v-model="auditForm.docCode"
                disabled
                placeholder="系统自动填充"
            />
        </el-form-item>

        <el-form-item label="审核人：" prop="auditor">
            <el-select
                v-model="auditForm.auditor"
                placeholder="请选择审核人"
                filterable
                clearable
                style="width: 100%"
            >
                <el-option
                   v-for="user in userList"
                  :key="user.id"
                  :label="`${user.name} `"
                  :value="user.id"
                />
            </el-select>
        </el-form-item>

        <el-form-item label="审批意见：" prop="comment">
            <el-input
                v-model="auditForm.comment"
                type="textarea"
                :rows="3"
                placeholder="请输入审批意见"
                maxlength="200"
                show-word-limit
            />
        </el-form-item>
        <el-form-item label="审核结果：" prop="checkResult">
            <el-select
                v-model="auditForm.checkRes"
                placeholder="请选择审核结果"
                style="width: 100%"
            >
                <el-option label="通过" :value="true" />
                <el-option label="不通过" :value="false" />
            </el-select>
        </el-form-item>

    </el-form>

    <template #footer>
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">提交审核</el-button>
    </template>
</el-dialog>





</template>



<script setup lang="ts">
import { ref,reactive, toRaw } from 'vue';
 import axios from 'axios';
 import { useRoute,useRouter } from 'vue-router';
 import type { CwOtherIncome,CwOtherIncomeDetail } from '@/types/public-xs/CwOtherIncome';
 import {ElMessage,ElMessageBox} from 'element-plus';
 import SalesCollectionPage from './SalesCollectionPage.vue';
 import SalesOrderPage from '@/sales-order/SalesOrderPage.vue';
import request from '@/util/request';
import type { User } from '@/types/rs/User';


 
 let pageNo=ref(1)
 let pageSize=ref(3)
 let allPage=ref(0)
 let route=useRoute()
 let router=useRouter()
 let docCode=ref('')

 const dueDate = ref(new Date())

// 设置为明年的今天
const setDueDateToNextYear = () => {
  const currentDate = new Date() // 获取当前日期
  const nextYearDate = new Date(
    currentDate.getFullYear() + 1,
    currentDate.getMonth(),
    currentDate.getDate()
  )
  
  // 处理闰年边缘情况（如2024-02-29 → 2025-03-01）
  dueDate.value = nextYearDate
}

setDueDateToNextYear


let cwOtherIncome=ref<CwOtherIncome>()
let cwOtherIncomeDetail=ref<CwOtherIncomeDetail>()

let userList=ref<User[]>([])
let selectUser=async()=>{
  let response=await request.post('/per/user/getAll')
  userList.value=response.data.data
  console.log(userList.value)
}
selectUser()

// 新增响应式数据
const auditDialogVisible = ref(false);
const auditFormRef = ref();
const auditForm = reactive({
    docCode: '',
    auditor: '',
    comment: '',
    checkRes: null
});

// 审核人列表（示例数据）
const auditors = ref([
    { id: 1, name: '张经理', dept: '财务部' },
    { id: 2, name: '李主管', dept: '销售部' }
]);

// 表单验证规则
const auditRules = reactive({
    auditor: [{ required: true, message: '请选择审核人', trigger: 'change' }],
    comment: [{ required: true, message: '请输入审批意见', trigger: 'blur' }],
    checkRes: [{ required: true, message: '请选择审核结果', trigger: 'change' }]
});

 const form = reactive({
   docNumber: '',
   stage: 'active',
   dateRange: [],
   invalid: 'no',
   subject: ''
 })
 const handleQuery = () => {
     // 重置为第一页
     pageNo.value = 1
     // 传递表单查询参数
     fetchData(pageNo.value, {
         docCode: form.docNumber,
         stage: form.stage,
         invalid: form.invalid,
         startDate: form.dateRange[0] ? formatDate(form.dateRange[0]) : undefined,
         endDate: form.dateRange[1] ? formatDate(form.dateRange[1]) : undefined
     })
 }
 
 const handleReset = () => {
   Object.assign(form, {
     docNumber: '',
     stage: 'active',
     dateRange: [],
     invalid: 'no',
     subject: ''
   })
 }
 
 const toggleCollapse = () => {
   // 收起/展开逻辑
 }
 
 const tableColumns = ref([
   { prop: 'createTime', label: '单据日期' ,width:200},
   { prop: 'docCode', label: '单据编号' ,width:200},
   { prop: 'cidStr', label: '客户' },
   { prop: 'uidStr', label: '业务员', width:100},
   { prop: 'didStr', label: '部门' },
   { prop: 'status', label: '状态' },
   { prop: 'totalAmount', label: '其他收款总金额' ,width:150 },
   { prop: 'createBy', label: '创建人' },
   { prop: 'updateBy', label: '修改人' },
   { prop: 'updateTime', label: '最后一次修改时间',width:200  },
   { prop: 'notes', label: '备注' },
 ])
 
 let tableData=ref<CwOtherIncome[]>([])
     const handlePageChange = (newPage: number) => {
   pageNo.value = newPage;
   fetchData(newPage);
 }
 const formatDate = (date: Date, isEndDate: boolean = false) => {
     const pad = (num: number) => num.toString().padStart(2, '0');
     const year = date.getFullYear();
     const month = pad(date.getMonth() + 1);
     const day = pad(date.getDate());
     
     // 如果是结束日期，时间设为 23:59:59
     if (isEndDate) {
         return `${year}-${month}-${day} 23:59:59`;
     }
     return `${year}-${month}-${day} 00:00:00`;
 };
 
 
 const handleTableAction = (actionName: string) => {
       switch(actionName){
         case 'add':
           router.push('/home/addCwOtherIncome')
           break
         case'check':
        //  handleCheck()
           break;
       }
     }
 
     async function fetchData(page: number, queryParams?: any) {
       const [startDate, endDate] = form.dateRange || []
      const params = {
             pageNo: page,
             pageSize: pageSize.value,
             doccCode: form.docNumber,
             stage: form.stage,
             invalid: form.invalid,
             startDate: startDate ? formatDate(startDate) : undefined,
             endDate: endDate ? formatDate(endDate) : undefined
         }
 
     let response=await request.post('/cw/CwOtherIncomeController/selectCwOtherIncomeByPage',{
       ...params,
       ...queryParams
     })
     tableData.value=response.data.data.list
     console.log(tableData.value)
     allPage.value=response.data.data.total
    
 }
 fetchData(1)
 const upDateSalesQuotes=(row: CwOtherIncome)=>{
   router.push({
     name:'UpdateCwOtherIncome',
     params:{ 
       docCode: row.docCode // 传递单据编号
     }
   })
   
 }



 // 监听子组件选择事件


const selectedOrder = ref<CwOtherIncome[]>([])


// 监听子组件选择事件
const handleSelectionChangeOrder = (selection: CwOtherIncome[]) => {
    selectedOrder.value = selection.map(row => row)
    console.log("拿对象", selectedOrder.value )
}



 //审核方法
const handleRowAudit = (row: CwOtherIncome) => {
    auditForm.docCode = row.docCode
    auditDialogVisible.value = true
    console.log('当前审核单据:', row.docCode)
}

//删除方法
const deleteDoc = async (row: CwOtherIncome) => {
  try {
    // 1. 弹出确认框
    await ElMessageBox.confirm(
      '此操作将永久删除该销售报价单，是否继续？',
      '警告',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
        // 可添加关闭前回调等其他配置
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true; // 确认按钮加载状态
            setTimeout(() => {
              done();
              instance.confirmButtonLoading = false;
            }, 300);
          } else {
            done();
          }
        }
      }
    );

    // 2. 用户确认后执行删除请求
    const response = await request.post('/cw/CwOtherIncomeController/deleteCwOtherIncome', {
      docCode: row.docCode
    });

    // 3. 处理响应结果
    if (response.data.code == 200) {
      ElMessage.success('删除成功');
      fetchData(1);
    } else {
      ElMessage.error('删除失败');
    }
  } catch (error) {
    // 4. 用户点击取消或关闭弹窗时触发 catch
    if (error === 'cancel') {
      ElMessage.info('已取消删除');
    } else {
      ElMessage.error('请求异常：' + error);
    }
  }
};


const submitAudit = async () => {
    // 表单验证
    if (!await auditFormRef.value?.validate()) return;



    try {
        const response = await request.post('/cw/CwOtherIncomeController/checkCwOtherIncome', {
            docCode: auditForm.docCode,
            typeId: 2,
            status: 3,
            checkManId: auditForm.auditor,  // 绑定审核人ID
            checkComment: auditForm.comment, // 绑定审批意见
            checkRes: auditForm.checkRes // 绑定审核结果
        });

        ElMessage.success(response.data.message);
        auditDialogVisible.value = false;
        fetchData(pageNo.value); // 刷新表格数据
    } catch (error) {
        ElMessage.error('审核提交失败');
    } finally {
        // 重置表单
        auditForm.auditor = '';
        auditForm.comment = '';
    }
};

</script>


<style scoped>


</style>